package com.secsbrain.development.biz.utils;

import com.alibaba.fastjson.JSON;
import com.secsbrain.common.ErrorCodeEnum;
import com.secsbrain.common.ResponseVo;
import com.secsbrain.common.spring.PropertyConfigurer;
import com.secsbrain.common.utils.HttpClientUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

/**
 * 钉钉相关工具类
 */
public class DingUtils {

    private static final Logger log = LoggerFactory.getLogger(DingUtils.class);

    /**
     * 钉钉群组消息通知
     *
     * @param tenantCode 租户编号
     * @param content    消息内容
     * @param mobileList 需要@的人的手机号，不@就传空
     * @return
     */
    public static ResponseVo<?> groupNotice(String tenantCode, String content, List<String> mobileList) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("msgtype", "text");

            Map<String, Object> textMap = new HashMap<>();
            textMap.put("content", content);
            map.put("text", textMap);

            if (CollectionUtils.isNotEmpty(mobileList)) {
                Map<String, Object> atMap = new HashMap<>();
                String[] mobileArray = mobileList.toArray(new String[mobileList.size()]);
                atMap.put("atMobiles", mobileArray);
                map.put("at", atMap);
            }

            String secret = PropertyConfigurer.getContextProperty("dinggroup.secret." + tenantCode);
            String url = PropertyConfigurer.getContextProperty("dinggroup.url." + tenantCode);
            long timestamp = System.currentTimeMillis();
            String stringToSign = timestamp + "\n" + secret;

            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));

            String sign = URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), "UTF-8");
            String result = HttpClientUtil.postRequest(url + "&timestamp=" + timestamp + "&sign=" + sign, JSON.toJSONString(map));
            Map<String, Object> resultMap = JSON.parseObject(result, Map.class);
            if ((Integer) resultMap.get("errcode") == 0) {
                return ResponseVo.getSuccessResponse();
            } else {
                log.error("钉钉异常:{},{}", resultMap.get("errcode"), resultMap.get("errmsg"));
                return ErrorCodeEnum.getEnumByCode((Integer) resultMap.get("errcode")).getResponseVo((String) resultMap.get("errmsg"));
            }
        } catch (Exception e) {
            return ErrorCodeEnum.ERROR_COMMON_SYSTEM.getResponseVo(e.getMessage());
        }

    }

}
